<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-col :span="5" class="labClass">
          <div class="grid-content bg-purple">
            <span>角色名:</span>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="grid-content bg-purple-light">
            <el-input v-model="roleName" placeholder="请输入"></el-input>
          </div>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="5" class="labClass">
          <div class="grid-content bg-purple">
            <span>拥有权限:</span>
          </div>
        </el-col>
        <el-col>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(city,index) in cities" :label="city.powerId" :key="index">{{ city.function }}
            </el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
      <p/>

      <p/>


      <el-button type="success" @click="add">添加</el-button>


    </el-card>

  </div>
</template>

<script>
export default {
  name: "addRole",
  data() {
    return {
      roleName: '',

      //初始化的数组
      cityOptions: [],
      //默认全选框是否被选中
      checkAll: false,
      //默认会选中的按钮，选中是按label里的值来判定的
      checkedCities: [],
      //初始化所有框体
      cities: this.cityOptions,
      isIndeterminate: false,
      //记录所有label的值，用于全选框判定是否全选
      roleIdArray: [],


      havenRoleId:[],
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.$axios.get('drp/Power/findByAll').then(
          r => {
            if (r.data != '') {
              this.cities = r.data
              console.log(r.data)
              for (let i = 0; i < r.data.length; i++) {
                this.cityOptions.push(r.data[i])
                this.roleIdArray.push(r.data[i].powerId)
              }
            }
          }
      )
    },
    add() {
      let formData=new FormData()
      formData.append("roleName",this.roleName)
      formData.append("powerIdArray",this.havenRoleId)
      this.$axios.post('drp/role/addRole',formData).then(
          r=>{
            if (r.data=='ok'){
              alert('添加角色成功')
              location.href='/index'
            }
          }
      )
    },
    handleCheckAllChange(val) {
      this.havePower = []
      this.checkedCities = val ? this.roleIdArray : [];
      this.havenRoleId=this.roleIdArray
      this.isIndeterminate = false;

    },
    handleCheckedCitiesChange(value) {
      this.havenRoleId=value
      console.log(this.havenRoleId)
      this.havePower = []
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    }
  }
}
</script>

<style scoped>

</style>